<!-- 文字横向滚动 -->
<template>
  <div class="roll-box">
    <div class="marquee-box">
      <img class="notice-img" src="@/assets/images/notice.png" alt="" />
      <p ref="cmdlist" id="pWidth">
        {{ content }}
      </p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'InlineRoll',
  props:{
    content: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      timer: '', // 计时器
      value: 0,
      pwidth: 0, // 公告文本的宽度
    }
  },
  mounted() {
    this.getWidth();
  },
  beforeDestroy() {
    this.end();
  },
  watch:{
    value(newValue, oldValue) {
      if(newValue && newValue <= -this.pwidth) {
        this.end();
        this.value = 0;
        this.$refs.cmdlist.style.marginLeft = this.value + "px";
        setTimeout(() => {
          this.start();
        }, 3000)
      }
    },
    content(newValue, oldValue) {
      if(newValue) {
        this.end();
        this.value = 0;
        this.$refs.cmdlist.style.marginLeft = this.value + "px";
        this.getWidth();
        setTimeout(() => {
          this.start();
        }, 3000)
      }
    }
  },
  methods: {
    getWidth() {
      let element = this.$refs.cmdlist;
      this.pwidth = document.defaultView.getComputedStyle(element, '').width.split('px')[0];
    },
    // 开始滚动
    start() {
      this.timer = setInterval(this.clickCommend, 20);
    },
    // 停止滚动
    end() {
      clearInterval(this.timer);
    },
    clickCommend(e) {
      this.$nextTick(() => {
        this.value -= 1;
        this.$refs.cmdlist.style.marginLeft = this.value + "px";
      });
    }
  }
}
</script>

<style scoped>
.roll-box {
  width: 50%;
  height: 50px;
}
.marquee-box {
  display: flex;
  align-items: center;
  position: relative;
  width: 100%;
  height: 100%;
  overflow: auto;
  /* background-color: #f8f8f8; */
}
.notice-img {
  display: inline-block;
  width: 40px;
  height: 40px;
  z-index: 99;
}
#pWidth {
  width: 100%;
  height: 50px;
  padding: 0;
  margin: 0;
  line-height: 50px;
  display: inline-block;
  word-break: keep-all;
  white-space: nowrap;
  overflow: hidden;
}
::-webkit-scrollbar {
  width: 0 !important;
}
::-webkit-scrollbar {
  width: 0 !important;height: 0;
}
</style>
